package com.charles.seckillComponentCommon.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.charles.seckillComponentCommon.constants.RoleConstants;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Charles-H
 * 
 * 线程处理 上下文绑定
 */
public class ThreadContext {

    /**
     * TTL线程
     */
    public static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * set
     */
    public static void set(String key, Object obj) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put(key, obj == null ? "" : obj);
    }

    /**
     * get
     */
    public static String get(String key) {
        Map<String, Object> localMap = getLocalMap();
        if (localMap.get(key) == null) {
            return "";
        }
        if (localMap.get(key) instanceof String) {
            return (String) localMap.get(key);
        }
        return localMap.get(key).toString();
    }

    /**
     * 泛型T get
     */
    @SuppressWarnings("unchecked")
    public static <T> T get(String key, Class<T> tClass) {
        Map<String, Object> localMap = getLocalMap();
        return (T) localMap.getOrDefault(key, null);
    }

    /**
     * 获取当前map
     */
    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        // 如果map为空，则创建一个线程安全的Hashmap
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    /**
     * 设置客户id
     */
    public static void setUserId(String userId) {
        set(RoleConstants.USER_ID, userId);
    }

    /**
     * 获取客户id
     */
    public static String getUserId() {
        return get(RoleConstants.USER_ID);
    }

    /**
     * 设置客户token
     */
    public static void setUserKey(String userKey) {
        set(RoleConstants.USER_KYE, userKey);
    }

    /**
     * 获取客户token
     */
    public static String getUserKey() {
        return get(RoleConstants.USER_KYE);
    }

    /**
     * 设置客户名称
     */
    public static void setUsername(String username) {
        set(RoleConstants.USERNAME, username);
    }

    /**
     * 获取客户名称
     */
    public static String getUsername() {
        return get(RoleConstants.USERNAME);
    }

    /**
     * 设置客户身份证号码
     */
    public static void setUserCard(String userCard) {
        set(RoleConstants.USER_CARD, userCard);
    }

    /**
     * 获取客户身份证号码
     */
    public static String getUserCard() {
        return get(RoleConstants.USER_CARD);
    }

    /**
     * 移除当前线程
     */
    public static void removeThread() {
        THREAD_LOCAL.remove();
    }

}
